# -*- coding: utf-8 -*-
# Este modulo se encargará de dar formato a la salida por la consola

from jiskolib import recibir, enviar
from time import sleep
from re import sub, match
from toolbox import list_diff, ENCODING, formatString, getColor

NOTES_PER_INTERVAL = 20
SLEEP_TIME = 180

def clr(s, c):
	if cfg and cfg['color']:
		return formatString(s, cfg['clr_' + c])
	else:
		return s

def clr_replies(s):
	return " ".join([word_clr(word) for word in s.split()])

def word_clr(w):
	if w[0] in ['@']:
		if not match('\W', w[-1]):
			return clr(w, 'reply')
		else:
			return clr(w[:-1], 'reply') + w[-1]
	else:
		return w

def show_loop(username=False, apikey=False, cfg=False):
	global color
	color = cfg and cfg['color']
	globals()['cfg'] = cfg
	print ''
	notelist = ['foo']
	while 1:
		try:
			print 'Actualizando'
			new_notes = recibir(NOTES_PER_INTERVAL)
			#print new_notes
			new_notes = list_diff(notelist, recibir(new_notes))
			#print new_notes
			notelist_print(new_notes)
			notelist = new_notes + notelist
			sleep(SLEEP_TIME)
		except (EOFError, KeyboardInterrupt):
			if not username or not apikey:
				break
			try:
				resp = unicode(raw_input("Introduzca el texto de la nota o introduzca 'quit' o 'exit' para cerrar Pysko\n> "), ENCODING)
			except (EOFError, KeyboardInterrupt):
				print ''
				break
			if resp in ['quit', 'exit']:
				break
			else:
				enviar(username, apikey, resp, True)

def notelist_print(nl):
	for i in range(len(nl)):
		note_print(nl[-(i + 1)])

def note_print(note):
	print clr(note[0], 'user')
	print clr('=' * len(note[0]), 'sep')
	print clr_replies(note[1])
	print ''
